package cn.com.ayqu.module.erp.dal.mysql.sale;

import cn.com.ayqu.framework.common.pojo.PageResult;
import cn.com.ayqu.framework.mybatis.core.mapper.BaseMapperX;
import cn.com.ayqu.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.com.ayqu.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.com.ayqu.module.erp.controller.admin.sale.vo.customer.ErpCustomerPageReqVO;
import cn.com.ayqu.module.erp.dal.dataobject.sale.ErpCustomerCarNumberDO;
import cn.com.ayqu.module.erp.dal.dataobject.sale.ErpCustomerDO;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * ERP 客户 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface ErpCustomerMapper extends BaseMapperX<ErpCustomerDO> {

    default PageResult<ErpCustomerDO> selectPage(ErpCustomerPageReqVO reqVO) {
        MPJLambdaWrapperX<ErpCustomerDO> query = new MPJLambdaWrapperX<ErpCustomerDO>()
                .likeIfPresent(ErpCustomerDO::getMobile, reqVO.getMobile())
                .orderByDesc(ErpCustomerDO::getId);

        if (StringUtils.isNotBlank(reqVO.getName())) {
            query.leftJoin(ErpCustomerCarNumberDO.class, ErpCustomerCarNumberDO::getCustomerId, ErpCustomerDO::getId)
                    .and(q -> {
                        q.like(ErpCustomerCarNumberDO::getCarNumber, reqVO.getName())
                                .or()
                                .like(ErpCustomerDO::getName, reqVO.getName())
                                .or()
                                .like(ErpCustomerDO::getAlias, reqVO.getName())
                                .selectAll(ErpCustomerDO.class);
                    })
                    .groupBy(ErpCustomerDO::getId);
        }

        if (reqVO.getUserIds() != null && !reqVO.getUserIds().isEmpty()) {
            query.in(ErpCustomerDO::getId, reqVO.getUserIds());
        }

        return selectPage(reqVO, query);
    }

    default List<ErpCustomerDO> selectListByStatus(Integer status) {
        return selectList(ErpCustomerDO::getStatus, status);
    }

}